package com.ccjq.yaoqing.core;

import java.sql.*;

/**
 * describe: 数据库连接工具类
 *
 * @author xugang
 * @date 2018/11/1 9:05
 */
public class DbConnection {

    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    static {
        DbConfigReader dbConfigReader = new DbConfigReader();
        DRIVER = dbConfigReader.getValue("db.driver");
        URL = dbConfigReader.getValue("db.url");
        USERNAME = dbConfigReader.getValue("db.username");
        PASSWORD = dbConfigReader.getValue("db.password");
    }

    /**
     * 建立数据库连接
     *
     * @return 连接对象
     */
    public static Connection getConnection() {
        Connection connection = null;

        try {
            Class.forName(DRIVER);
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;
    }

    /**
     * 关闭数据库连接
     *
     * @param rs   结果集对象
     * @param st   语句对象
     * @param conn 连接对象
     */
    public static void close(ResultSet rs, Statement st, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }

            if (st != null) {
                st.close();
            }

            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(DbConnection.getConnection());
    }
}
